<template>
  <div style="margin: 10px;">
    <el-breadcrumb separator-class="el-icon-arrow-right"
                   style="margin-bottom: 10px;">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
    </el-breadcrumb>

    <el-tabs tab-position="left"
             v-model="activeTab"
             @tab-click="getPosts">

      <!-- 基本信息 -->
      <el-tab-pane label="基本信息"
                   name="basicInfo"
                   id="basicInfo">
        <div style="margin: 10px;">
          <span class="user-name">{{userInfo.userName}}</span>
          <span class="user-account">{{$store.getters.userAccount}}</span>
          <div class="user-info-row">性别：{{genderCN}}</div>
          <div class="user-info-row">年龄：{{userInfo.userAge}}</div>
          <div class="user-info-row">注册时间：{{userInfo.userTime}}</div>
          <div class="user-info-row"
               style="width: 600px;">个人简介：{{userInfo.userProfile}}</div>
        </div>
      </el-tab-pane>

      <!-- 修改信息 -->
      <el-tab-pane label="修改信息"
                   name="updateInfo"
                   id="updateInfo">
        <div style="margin: 10px; width: 600px;">
          <el-form :model="newInfo"
                   ref="newInfo"
                   :rules="rules"
                   label-width="80px">
            <el-form-item label="用户名:"
                          prop="userName">
              <el-input v-model="newInfo.userName"></el-input>
            </el-form-item>
            <el-form-item label="性别:"
                          prop="userGender">
              <el-radio-group v-model="newInfo.userGender">
                <el-radio label="male">男</el-radio>
                <el-radio label="female">女</el-radio>
                <el-radio label="others">其他</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄:"
                          prop="userAge">
              <el-input v-model="newInfo.userAge"></el-input>
            </el-form-item>
            <el-form-item label="简介:"
                          prop="userProfile">
              <el-input type="textarea"
                        :rows="6"
                        v-model="newInfo.userProfile"></el-input>
            </el-form-item>
            <el-form-item>
              <template>
                <el-popconfirm title="确定修改吗？"
                               @onConfirm="onModifyConfirm">
                  <el-button type="primary"
                             slot="reference">修改</el-button>
                </el-popconfirm>
              </template>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 我的帖子 -->
      <el-tab-pane label="我的帖子"
                   name="myPosts"
                   id="myPosts">
        <div style="margin: 10px;">
          <el-table :data="myPosts.slice((currentPage - 1) * 10, currentPage * 10)"
                    stripe>
            <el-table-column label="标题">
              <template slot-scope="scope">
                <router-link :to="{path:'/post', query:{id: scope.row.postID, title: scope.row.postTitle, announcement:0}}">{{scope.row.postTitle}}</router-link>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="partitionName"
                             label="板块">
            </el-table-column> -->
            <el-table-column prop="postTime"
                             label="发帖时间">
            </el-table-column>
            <el-table-column prop="postReplyTime"
                             label="最后回复时间">
            </el-table-column>
            <el-table-column prop="postRepCount"
                             label="回复数">
            </el-table-column>
          </el-table>
          <el-pagination @current-change="currentChange"
                         :current-page="currentPage"
                         :page-size="10"
                         layout="total, prev, pager, next, jumper"
                         :total="myPosts.length"
                         :hide-on-single-page="true">
          </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
export default {
  name: 'User',
  data () {
    var validateAge = (rule, value, callback) => {
      if (/^\d+$/.test(value)) callback()
      else callback(new Error('请输入正确的年龄'))
    }
    return {
      activeTab: 'basicInfo',
      currentPage: 1,
      userInfo: {
        userName: '',
        userID: '',
        userGender: 'male',
        userAge: 0,
        userTime: '',
        userProfile: ''
      },
      newInfo: {},
      myPosts: [],
      rules: {
        userAge: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          { validator: validateAge, trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    genderCN () {
      if (this.userInfo.userGender === 'male') return '男'
      else if (this.userInfo.userGender === 'female') return '女'
      else return '其他'
    }
  },
  mounted () {
    this.newInfo = JSON.parse(JSON.stringify(this.userInfo)) // 深拷贝，修改newInfo不会影响userInfo

    console.log('user mounted')

    // get user info
    this.refreshInfo()
  },
  methods: {
    onModifyConfirm () {
      var updateInfo = document.getElementById('updateInfo')
      const updateInfoLoading = this.$loading.service({
        target: updateInfo
      })
      this.$refs.newInfo.validate((valid) => {
        if (valid) {
          this.axios.post('setInfo', {
            userID: this.$store.getters.userID,
            userName: this.newInfo.userName,
            userGender: this.newInfo.userGender,
            userAge: Number(this.newInfo.userAge),
            userProfile: this.newInfo.userProfile
          })
            .then(response => {
              if (response.status === 200) {
                if (response.data.err === 200) {
                  // Todo: get userInfo again
                  // this.userInfo = JSON.parse(JSON.stringify(this.newInfo))
                  // this.userInfo.age = parseInt(this.userInfo.age)
                  this.userInfo = response.data
                  this.$notify({
                    title: '提示',
                    message: '修改成功',
                    position: 'top-left'
                  })
                  updateInfoLoading.close()
                  this.activeTab = 'basicInfo'
                } else {
                  this.$notify({
                    title: '修改失败',
                    message: response.data.message,
                    position: 'top-left'
                  })
                  updateInfoLoading.close()
                }
              } else {
                this.$notify({
                  title: '修改失败',
                  message: '网络错误',
                  position: 'top-left'
                })
                updateInfoLoading.close()
              }
            })
            .catch(error => {
              console.log(error)
              updateInfoLoading.close()
            })
        } else {
          this.$notify({
            title: '提示',
            message: '修改失败，请检查输入',
            position: 'top-left'
          })
          updateInfoLoading.close()
        }
      })
    },
    currentChange (page) {
      this.currentPage = page
      window.scrollTo(0, 0)
    },
    refreshInfo () {
      console.log('getting info')
      var basicInfo = document.getElementById('basicInfo')
      var updateInfo = document.getElementById('updateInfo')
      const basicInfoLoading = this.$loading.service({
        target: basicInfo
      })
      const updateInfoLoading = this.$loading.service({
        target: updateInfo
      })
      console.log('userID: ' + this.$store.getters.userID)
      console.log(typeof this.$store.getters.userID)
      this.axios.post('getinfo', {
        userID: this.$store.getters.userID
      })
        .then(response => {
          if (response.status === 200) {
            if (response.data.err === 200) {
              this.userInfo = response.data
              this.newInfo = JSON.parse(JSON.stringify(this.userInfo)) // 深拷贝，修改newInfo不会影响userInfo
              basicInfoLoading.close()
              updateInfoLoading.close()
            } else {
              this.$notify({
                title: '获取用户信息失败',
                message: response.data.message,
                position: 'top-left'
              })
              basicInfoLoading.close()
              updateInfoLoading.close()
            }
          } else {
            this.$notify({
              title: '获取用户信息失败',
              message: '网络错误',
              position: 'top-left'
            })
            basicInfoLoading.close()
            updateInfoLoading.close()
          }
        })
        .catch(error => {
          console.log(error)
          basicInfoLoading.close()
          updateInfoLoading.close()
        })
    },
    getPosts (tab) {
      if (this.activeTab === 'myPosts') {
        console.log('get posts')
        var myPosts = document.getElementById('myPosts')
        const myPostsLoading = this.$loading.service({
          target: myPosts
        })
        this.axios.post('getidpost', {
          userID: this.$store.getters.userID
        })
          .then(response => {
            if (response.status === 200) {
              if (response.data.err === 200) {
                this.myPosts = response.data.postList
                myPostsLoading.close()
              } else {
                this.$notify({
                  titile: '获取帖子列表失败',
                  message: response.data.message,
                  position: 'top-left'
                })
                myPostsLoading.close()
              }
            } else {
              this.$notify({
                titile: '获取帖子列表失败',
                message: '网络错误',
                position: 'top-left'
              })
              myPostsLoading.close()
            }
          })
          .catch(error => {
            console.log(error)
            myPostsLoading.close()
          })
      }
    }
  }
}
</script>

<style >
.user-name {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin-right: 5px;
}
.user-account {
  font-size: 7px;
  color: #909399;
}
.user-info-row {
  margin-top: 10px;
}
</style>
